PARENT_DIR:=$(shell basename $(CURDIR))
VERSION=0.0.0
COMMIT_FILE=.commit


.PHONY: help
help: # 显示帮助
	@echo -e "\033[32m使用方法: make [target]\033[0m"
	@echo
	@echo "Targets:"
	@echo "  proto    生成Protobuf代码"
	@echo "  dev      运行服务(开发模式)"
	@echo "  build    构建程序"
	@echo "  image    构建镜像(可选项: VERSION=v1.0.0)"
	@echo "  help     显示帮助"
	@echo

.PHONY: proto
proto: # 生成Protobuf代码
	@echo -e "\033[32m生成Protobuf代码\033[0m"
	@protoc --proto_path=.. \
    --go_out=.. --go_opt=paths=source_relative \
    --go-grpc_out=.. --go-grpc_opt=paths=source_relative \
    ../proto/**/*.proto

.PHONY: dev
dev: # 运行服务(开发模式)
	@echo -e "\033[32m运行服务(开发模式)\033[0m"
	@go run cmd/main.go --config=config/yaml/dev.yaml

.PHONY: build
build: # 构建程序
ifeq ($(wildcard $(COMMIT_FILE)),)
	@echo -e "\033[32m更新codebox-common模块\033[0m"
	@go get -u g.utobo.net/devops/codebox-common
	@echo -e "\033[32m未找到$(COMMIT_FILE)文件\033[0m"
	@echo -e "\033[32m程序构建\033[0m"
	@go build -ldflags "-X main.commit=$(shell git rev-parse HEAD) -w" -o ${PARENT_DIR} cmd/main.go
	@echo -e "\033[32m压缩程序\033[0m"
	@upx ${PARENT_DIR}
else
	@echo -e "\033[32m找到$(COMMIT_FILE)文件\033[0m"
	@echo -e "\033[32m程序构建\033[0m"
	@go build -ldflags "-X main.commit=$(shell cat $(COMMIT_FILE)) -w" -o ${PARENT_DIR} cmd/main.go
	@echo -e "\033[32m压缩程序\033[0m"
	@upx ${PARENT_DIR}
	@echo -e "\033[32m删除$(COMMIT_FILE)文件\033[0m"
	@rm -f $(COMMIT_FILE)
endif
	@echo -e "\033[32m完成\033[0m"

.PHONY: image
image: # 构建镜像(可选项: VERSION=v1.0.0)
	@echo -e "\033[32m更新codebox-common模块\033[0m"
	@go get -u g.utobo.net/devops/codebox-common
	@echo -e "\033[32m更新所有依赖\033[0m"
	@go mod tidy
	@echo -e "\033[32m创建本地依赖\033[0m"
	@GOWORK=off go mod vendor
	@echo -e "\033[32m生成$(COMMIT_FILE)\033[0m"
	@echo $(shell git rev-parse HEAD) > $(COMMIT_FILE)
	@echo -e "\033[32m构建镜像\033[0m"
	@docker build --progress=plain -t ccr.ccs.tencentyun.com/codebox/${PARENT_DIR}:${VERSION} -f ./Dockerfile .
	@echo -e "\033[32m推送镜像\033[0m"
	@docker push ccr.ccs.tencentyun.com/codebox/${PARENT_DIR}:${VERSION}
	@echo -e "\033[32m清理文件\033[0m"
	@rm -f $(COMMIT_FILE)
	@rm -rf vendor
	@echo -e "\033[32m完成\033[0m"
